import org.junit.Test;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 不知名网友鑫
 * @Date 2022/6/13
 * 获取文本上每个字符出现的次数，写入到文件中。
 * 提示：遍历文本的每一个字符；字符及出现的次数保存在Map中；将Map中数据写入文件
 **/
public class FileReaderWriterExer {

    @Test
    public void exe1() {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("Hello.txt");
            fw = new FileWriter("Count.txt");
            Map<Character, Integer> map = new HashMap<>();
            int b;
            int len;
            while ((len = fr.read()) != -1) {
                char c = (char) len;
                if (map.containsKey(c)) {
                    map.put(c, map.get(c) + 1);
                } else {
                    map.put(c, 1);
                }
            }
            for (Map.Entry<Character, Integer> entry : map.entrySet()) {
                switch (entry.getKey()) {
                    case ' ':
                        fw.write("空格=" + entry.getValue());
                        break;
                    case '\t'://\t表示tab 键字符
                        fw.write("tab键=" + entry.getValue());
                        break;
                    case '\r'://
                        fw.write("回车=" + entry.getValue());
                        break;
                    case '\n'://
                        fw.write("换行=" + entry.getValue());
                        break;
                    default:
                        fw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                fw.write("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
